package org.zhxy.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.zhxy.model.entity.Student;
import org.zhxy.model.result.Result;
import org.zhxy.service.StudentService;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
@Tag(name = "学生管理")
@RestController
@RequestMapping("/sms/studentController")
@RequiredArgsConstructor
public class StudentController {
    private final StudentService studentService;

    @Operation(summary = "分页条件查询学生列表")
    @GetMapping("/getStudentByOpr/{pageNo}/{pageSize}")
    public Result getStudentsByOpr(@PathVariable("pageNo") Integer pageNo, @PathVariable("pageSize") Integer pageSize, Student student) {
        log.info("分页条件查询学生列表，请求参数：{},{},{}", pageNo, pageSize, student);

        IPage<Student> page = new Page<>(pageNo, pageSize);
        studentService.page(page, student);
        log.info("分页条件查询学生列表，响应数据：{}", page);

        return Result.ok(page);
    }

    @Operation(summary = "保存或更新学生信息")
    @PostMapping("/addOrUpdateStudent")
    public Result addOrUpdateStudent(@RequestBody Student student) {
        log.info("保存或更新学生信息，请求参数：{}", student);

        // 对学生的密码进行加密
        if (!Strings.isEmpty(student.getPassword())) {
            String password = DigestUtils.md5DigestAsHex(student.getPassword().getBytes(StandardCharsets.UTF_8));
            student.setPassword(password);
        }
        // 保存学生信息进入数据库
        studentService.saveOrUpdate(student);
        return Result.ok();
    }

    @Operation(summary = "批量删除学生信息")
    @DeleteMapping("/delStudentById")
    public Result delStudentById(@RequestBody List<Integer> ids) {
        log.info("批量删除学生信息，请求参数：{}", ids);

        studentService.removeByIds(ids);
        return Result.ok();
    }
}
